function [idy, y] = dayavg(idx, x, mode)

   ## usage:  [idy, y] = dayavg (idx, x, mode)
   ## 
   ## calculate daily averages, mode=24 indicating 24h belongs to day

   pkg load nan
   wrn = warning("query", "Octave:divide-by-zero").state ;
   warning("off", "Octave:divide-by-zero") ;

   u = unique(idx(:,4)) ;

   if (nargin < 3 || mode == 0)
      h = min(u) ;
   else
      h = sort(u)(floor(length(u)/2)+1) ;
   endif

   if columns(idx) < 4
      [idy, y] = deal(idx, x) ;
      return
   endif

   if numel(u) < 5

      lb = find(idx(:,4) == h) ;
      ub = shift(find(idx(:,4) == h) - 1, -1) ; ub(end) = rows(idx) ;

      for j=1:rows(lb)
	 idy(j,:) = idx(lb(j),:) ;
	 y(j,:) = mean(x(lb(j):ub(j),:)) ;
      endfor
      idy(:,4) = 12 ;

   else

      rd = datenum(idx(:,1:3)) ;
      delta = diff(rdu = unique(rd)) ;
      for d = 1:length(rdu)
	 I = find(rd == rdu(d)) ;
	 idy(d,:) = idx(I(1),1:3) ;
	 y(d,:) = mean(x(I,:)) ;
      endfor

   endif

   warning(wrn, "Octave:divide-by-zero") ;

endfunction
